// 引入Vue Router
import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessageBox } from 'element-plus'

// 创建路由实例
const router = createRouter({
    // 路由模式
    history: createWebHashHistory(),
    routes: [
        // 配置默认页面
        {
            path: '/',
            redirect: '/home',
        },
        {
            name: 'home',
            path: '/home',
            component: () => import('../pages/Home.vue'),
            meta: { title: '首页' },
            redirect: '/video',
            children: [
                {
                    name: 'video',
                    path: '/video',
                    component: () => import('../pages/player/Player.vue'),
                    meta: { title: '推荐' }
                },
                {
                    name: 'videolist',
                    path: '/videolist',
                    component: () => import('../pages/list/VideoList.vue'),
                    meta: { title: '列表' }
                },
                {
                    name: 'followlist',
                    path: '/followlist',
                    component: () => import('../pages/list/FollowList.vue'),
                    meta: { title: '关注列表' }
                },
                {
                    name: 'collectlist',
                    path: '/collectlist',
                    component: () => import('../pages/list/CollectList.vue'),
                    meta: { title: '收藏列表' }
                },
                {
                    name: 'publish',
                    path: '/publish',
                    component: () => import('../pages/publish/PublishVideo.vue'),
                    meta: { title: '发布视频' }
                },
                {
                    name: 'searchlist',
                    path: '/searchlist',
                    component: () => import('../pages/list/SearchList.vue'),
                    meta: { title: '搜索列表' }
                },
            ]
        }
    ]
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
    const toPath = to.path
    // 对关注页面、收藏页面和发布页面进行守卫，需登录后才能访问
    const validPaths = ['/followlist', '/collectlist', '/publish'];
    if (validPaths.includes(toPath)) {
        const token = localStorage.getItem('Authorization')
        if (token === null) {
            // 如果未登录，弹出提示框
            ElMessageBox.alert('请先登录')
            next(false) // 取消导航
        } else {
            next(); // 继续导航
        }
    } else {
        // 对其他页面放行
        next();
    }
});

// 后置路由守卫
router.afterEach(function (to) {
    // 判断目标组件是否配置了title
    if (to.meta.title) {
        document.title = to.meta.title;
    } else {
        document.title = '牛视频';
    }
});

export default router;